package operatemodel

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
	"server/global"
	"server/model"
	entry "server/model/entrance"
	"server/myutils"
	"time"

	"github.com/go-redis/redis/v8"
)

func GetWeather() (data string, code int) {
	var time = time.Now().Format("2006-01-02")
Start:
	s, err := model.Redis.HGet(model.Ctx, "weather", time).Result()
	if err == redis.Nil {
		i := apigetweather(time)
		if i != global.SUCCESS {
			code = i
			data = ""
			return
		}
		goto Start
	}
	if err != nil {
		data = ""
		code = global.FAIL
		return
	}
	data = s
	code = global.SUCCESS
	return
}

func apigetweather(time string) (code int) {
	r, err := http.Get("http://t.weather.itboy.net/api/weather/city/" + myutils.WeatheCode)
	if err != nil {
		code = global.NOTFOUND
		return
	}
	defer r.Body.Close()           //关闭连接,防止内存泄漏
	b, _ := ioutil.ReadAll(r.Body) //json数据转struct
	var data = new(entry.Weather)  //struct什么格式json解析什么格式 struct转成json是会读取数据存储的
	json.Unmarshal(b, data)        //拼接成平行结构体存储
	var tdata = entry.TrueWeather{
		Date:    data.Data.Forecast[0].Date,
		Hight:   data.Data.Forecast[0].Hight,
		Low:     data.Data.Forecast[0].Low,
		Fl:      data.Data.Forecast[0].Fl,
		Week:    data.Data.Forecast[0].Week,
		Type:    data.Data.Forecast[0].Type,
		Notice:  data.Data.Forecast[0].Notice,
		City:    data.CityInfo.City,
		Citykey: data.CityInfo.Citykey,
	}
	jsondata, _ := json.Marshal(&tdata) //存储成json格式
	//存储进weather里面,key=time   i表示存储的字段数
	_, err2 := model.Redis.HSet(model.Ctx, "weather", time, string(jsondata)).Result()
	if err2 != nil {
		code = global.FAIL
		return
	}
	code = global.SUCCESS
	return
}

func Getflow() ([]map[string]interface{}, error) {
	//获取redis数据
	//过去7天的数据 --时间以定义好的时间为准
	var data = make([]map[string]interface{}, 0)
	for i := 0; i < 7; i++ {
		//Note:Sub只支持减time格式的数据 要减固定时间用:Add(-time)
		s, err2 := model.Redis.HGet(model.Ctx, "flow", myutils.Timeday.Add(-(time.Duration(i) * 24 * time.Hour)).Format("2006-01-02")).Result()
		if err2 == redis.Nil {
			continue
		} else if err2 != nil {
			return nil, errors.New("连接错误")
		}
		data = append(data, map[string]interface{}{
			"date": myutils.Timeday.Add(-(time.Duration(i) * 24 * time.Hour)).Format("2006-01-02"),
			"num":  s,
		})
	}
	return data, nil
}
